package com.example.exception;

import com.example.model.GeneralResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理器，每个异常处理器必须实现ExceptionMapper接口
 * 如果要处理特定异常，ExceptionMapper泛型必须指定该异常类型
 */
@Slf4j
@Provider
public class GlobalExceptionMapper implements ExceptionMapper<Exception> {

    /**
     * 自动注入已配置的Jackson处理器
     */
    @Inject
    ObjectMapper objectMapper;
    @Override
    public Response toResponse(Exception e) {
        try {
            GeneralResult<String> result = GeneralResult.error(e.getMessage());
            String jsonString = objectMapper.writeValueAsString(result);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(jsonString).build();
        } catch (JsonProcessingException ex) {
            log.error("JSON处理异常", ex);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }
}
